﻿#include "MarketTimeAmendment.h"
#include "Tools.h"
#include "CTPTime.h"
#include "MarketDataSource.h"

MarketTimeAmendment::MarketTimeAmendment()
{
	time_t cuTmt = Tools::GetCurrentTimeStamp();
	SetWorkTime(cuTmt);
}

MarketTimeAmendment::~MarketTimeAmendment()
{
}

void MarketTimeAmendment::SetWorkTime(time_t cuTmt)
{
	tm cuTM = Tools::GetDateTimeFrmStamp(cuTmt);
	tm pmarketBegin, pmarketEnd;
	CTPTm::GetSegmentMarketRange(cuTM, pmarketBegin, pmarketEnd);
	m_segmentBegin = Tools::GetTimeStamp(pmarketBegin);
	m_segmengEnd = Tools::GetTimeStamp(pmarketEnd);

	m_systemDay = Tools::GetDate(cuTM);
	m_systemTime = 0;
	m_todayStr = Tools::DateToStr(pmarketBegin);
}

MarketTimeAmendment & MarketTimeAmendment::Instance()
{
	static MarketTimeAmendment pMT;
	return pMT;
}

time_t MarketTimeAmendment::GetRealTime(char pDay[9], char pTime[9])
{
	time_t curTMStamp = 0;
	if (strlen(pDay) > 0)
	{
		m_systemDay = MDSrc::GetMarketDate(pDay);
		m_systemTime = MDSrc::GetDateTime(m_systemDay, pTime);
		curTMStamp = m_systemTime;
	}
	else
	{
		curTMStamp = MDSrc::GetDateTime(m_systemDay, pTime);
		if (m_systemTime > 0)
		{
			if (m_systemTime - curTMStamp > 10) // 这个时候可能是当前行情已经进入第二天，但上期或能源还没进来
			{
				tm newTM = Tools::AddDays(m_systemDay, 1);
				curTMStamp = MDSrc::GetDateTime(newTM, pTime);
			}
			else if (curTMStamp - m_systemTime > 10) // 这种情况可能是上期或能源进入第二天了，但当前合约还没进入
			{
				tm newTM = Tools::AddDays(m_systemDay, -1);
				curTMStamp = MDSrc::GetDateTime(newTM, pTime);
			}
		}
	}
	return curTMStamp;
}

//bool MarketTimeAmendment::IsInCurSegment(char pTime[9])
//{
//	time_t curTMStamp = GetRealTime(pTime);
//	return IsInCurSegment(curTMStamp);
//}

bool MarketTimeAmendment::IsInCurSegment(time_t pTime)
{
	if (pTime <= 0)
	{
		return false;
	}
	// 不在行情时间内就返回了
	if (pTime < m_segmentBegin || pTime > m_segmengEnd)
	{
		return false;
	}
	return true;
}
